<?php
/**
 * @see Service_Condition
 */
require_once 'Service/Condition.php';

/**
 * Group condition.
 *
 * Group can contain sub conditions. Subcondition can be instance of the
 * Service_Condition class or its child including a group condition class.
 *
 * @category Service
 * @package Condition
 *
 * @author r0b1n
 * @author Baziak
 */
class Service_Condition_ZendDb_Group extends Service_Condition
{
    const TYPE_AND = 'AND';
    const TYPE_OR  = 'OR';
    
    protected $_conds = array();
    protected $_type = self::TYPE_AND;

    /**
     * Constructor.
     *
     * @param string $type
     */
    public function __construct($type = self::TYPE_AND)
    {
        if (!empty($type)) {
            $this->_type = $type;
        }
    }

    /**
     * Converts to string.
     *
     * @return string
     */
    public function __toString()
    {
        $str = array();
        foreach ($this->_conds as $cond) {
            $str[] = "($cond)";
        }
        return implode(' ' . $this->_type . ' ', $str);
    }

    /**
     * Adds subcondition.
     *
     * @param Service_Condition $condition
     * @return Service_Condition_Group
     */
    public function add(Service_Condition $condition, $name = null)
    {
        $condition->setDataSource($this->getDataSource());

        if (null === $name) {
            array_push($this->_conds, $condition);
        } else {
            $this->_conds[$name] = $condition;
        }
        return $this;
    }

    public function get($name)
    {
        return isset($this->_conds[$name]) ? $this->_conds[$name] : null;
    }

    /**
     * Clears filter.
     *
     * @return Service_Condition_Group
     */
    public function clear()
    {
        $this->_conds = array();
        return $this;
    }

    /**
     * Sets Data Source for all subconditions.
     *
     * @param Service_DataSource $ds
     * @return Service_Condition_Group
     */
    public function setDataSource($ds)
    {
        parent::setDataSource($ds);
        
        foreach ($this->_conds as $condition) {
            $condition->setDataSource($ds);
        }

        return $this;
    }
}
